﻿using System.Configuration;
using LL.Data;
using FluentData;

namespace LL.Data.FluentData
{
    /// <summary>
    /// 数据库会话工厂
    /// </summary>
    public class DbSessionFactory : IDbSessionFactory
    {
        
        public DbSessionFactory()
        {
            //
        }

        /// <summary>
        /// 返回新数据库会话实例
        /// </summary>
        /// <remarks>使用配置的默认数据库连接</remarks>
        /// <remarks>默认不使用事务</remarks>
        /// <param name="keepAlive">保持数据库连接</param>
        public IDbSession NewSession(bool keepAlive = false)
        {
            return NewSession(GetDefaultName(), keepAlive);
        }

        /// <summary>
        /// 返回新数据库会话实例
        /// </summary>
        /// <remarks>默认不使用事务</remarks>
        /// <param name="connectionName">数据库连接名称</param>
        /// <param name="keepAlive">保持数据库连接</param>
        public IDbSession NewSession(string connectionName, bool keepAlive = false)
        {
            var dbContext = new DbContext()
                .ConnectionStringName(connectionName, new SqlServerProvider())
                .UseSharedConnection(keepAlive);

            return new DbSession(dbContext);
        }

        /// <summary>
        /// 根据配置文件获取默认数据库连接名
        /// </summary>
        static string GetDefaultName()
        {
            string contextName =
                ConfigurationManager.AppSettings["DefalutConnectionName"];
            if (string.IsNullOrEmpty(contextName))
                contextName = ConfigurationManager.ConnectionStrings[0].Name;
            return contextName;
        }
    }
}
